package cn.smbms.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smbms.pojo.Product;
import cn.smbms.pojo.Type;
import cn.smbms.service.product.ProductService;
import cn.smbms.service.type.TypeService;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("/type")
public class TypeController {
	private Logger logger = Logger.getLogger(TypeController.class);
	@Resource
	private TypeService typeService;
	@Resource
	private ProductService productService;

	@RequestMapping("/assort")
	public String getTypeList(Model model) {
		List<Type> typeList = null;
		try {
			typeList = typeService.getTypeList();
			model.addAttribute("typeList", typeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "assort";
	}

	// product.jsp页面显示所有类别
	@RequestMapping("/getTypeList")
	@ResponseBody
	public Object getList(Model model) {
		List<Type> typeList = null;
		try {
			typeList = typeService.getTypeList();
			model.addAttribute("typeList", typeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSON.toJSONString(typeList);
	}

	@RequestMapping("/getProductByTypeId")
	@ResponseBody
	public List<Product> getProductByTypeId(
			@RequestParam(value = "typeId", required = false) String typeId) {

		List<Product> productList = null;
		// 控制商品分类ID合法性
		if (StringUtils.isNullOrEmpty(typeId)) {
			typeId = "1";
		}
		Integer id = Integer.parseInt(typeId);
		productList = productService.getImgsByTypeId(id);
		return productList;
	}

	@RequestMapping("/getTypeById")
	@ResponseBody
	public Type getTypeById(
			@RequestParam(value = "typeId", required = false) String typeId) {
		Type type = null;
		if (StringUtils.isNullOrEmpty(typeId)) {
			typeId = "1";
		}
		Integer id = Integer.parseInt(typeId);
		try {
			type = typeService.getTypeById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return type;
	}
}
